package com.lm56.web.sys.service;

import com.lm56.common.Pinyin4jUtils;
import com.lm56.common.ServiceException;
import com.lm56.common.Utils;
import com.lm56.common.exception.FieldValidateExcetiption;
import com.lm56.common.exception.UserAlreadyExistsException;
import com.lm56.common.MyMd5PasswordEncoder;
import com.lm56.web.security.SecUserDetails;
import com.lm56.web.sys.domain.User;
import com.lm56.web.sys.domain.UserContact;
import com.lm56.web.sys.domain.UserDetail;
import com.lm56.web.sys.mapper.UserMapper;
import com.lm56.web.network.domain.Location;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.Security;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Kelvin Yeung on 2016/10/20.
 */

@Service("userService")
@Transactional
public class UserService {

    @Resource
    UserMapper userMapper;

    public List<User> getAllUsers() {
        return userMapper.getAllUsers();
    }

    public User getUserByPhoneNoOrEmail(String phoneNoOrEmail) {
        if (phoneNoOrEmail.indexOf("@") != -1) {
            return userMapper.getUserByEmail(phoneNoOrEmail);
        } else {
            return userMapper.getUserByPhoneNo(phoneNoOrEmail);
        }


    }


    public User getUserById(long id) {
        return userMapper.getUserById(id);
    }

    public User getUserByPhoneNo(String phoneNo) {
        return userMapper.getUserByPhoneNo(phoneNo);
    }

    public User getUserByEmail(String email) {
        return userMapper.getUserByEmail(email);
    }


    public UserDetail getUserDetailById(long id) {
        return userMapper.getUserDetailById(id);
    }

    public UserDetail getUserDetailByPhoneNo(String phoneNo) {
        return userMapper.getUserDetailByPhoneNo(phoneNo);
    }

    public void addUser(UserDetail userDetail) {

        User user1 = getUserByPhoneNo(userDetail.getPhoneNo());
        if (user1 != null) {
            throw new UserAlreadyExistsException("此手机号已在平台注册,请使用其他手机注册", "phoneNo");
        }
//        User user2 = getUserByPhoneNo(userDetail.getEmail());
//        if(user2 != null){
//            throw new UserAlreadyExistsException("此邮箱已在平台注册，请使用其他邮箱注册","email");
//        }

        //encrypt password
        MyMd5PasswordEncoder pwdEncoder = new MyMd5PasswordEncoder();
        String salt = MyMd5PasswordEncoder.genSalt();
        //add salt value
        String encodePwd = pwdEncoder.encodePassword(userDetail.getPassword(), salt);
        userDetail.setSalt(salt);
        userDetail.setPassword(encodePwd);


        try {
            String  f = Pinyin4jUtils.getFirstLetter(userDetail.getUserName());
            userDetail.setFirstLetterOfName(f);
        }catch (Exception e){
            userDetail.setFirstLetterOfName("UNKNOW");
        }
        try {

            userMapper.insertUser(userDetail);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        long userId = userDetail.getId();

        //set userId into userContat
        List<UserContact> contacts = userDetail.getContactList();
        if (contacts != null) {
            for (UserContact contact : contacts) {
                contact.setUserId(userId);
            }
            try {
                userMapper.insertUserContacts(contacts);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }

        }


        //set userId into lines
        List<Location> lines = userDetail.getLines();
        if (lines != null && lines.size() > 0) {

            try {
                userMapper.insertRegularLines(userId, lines);

            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }

        }


        //TODO:公司的主营路线不插入数据库，但要生成路线；


    }


    public void changePassowrd(String oldPwd, String newPwd) {
        if (StringUtils.isBlank(oldPwd)) {
            throw new FieldValidateExcetiption("oldPwd", "旧密码不能为空");
        }
        if (StringUtils.isBlank(newPwd)) {
            throw new FieldValidateExcetiption("newPwd", "新密码不能为空");
        }
        if (!Utils.isValidPassword(newPwd)) {
            throw new FieldValidateExcetiption("newPwd", "由字母或数字组成，长度在6~18之间，只能包含字符、数字和下划线");
        }
        SecUserDetails secUser = (SecUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        secUser.getPassword();
        MyMd5PasswordEncoder pwdEncoder = new MyMd5PasswordEncoder();
        String tmpPwd = pwdEncoder.encodePassword(oldPwd, secUser.getSalt());
        if (!tmpPwd.equals(secUser.getPassword())) {
            throw new FieldValidateExcetiption("oldPwd", "旧密码不正确");
        }
        String salt = MyMd5PasswordEncoder.genSalt();
        String newMd5Pwd = pwdEncoder.encodePassword(newPwd, salt);

        User user = userMapper.getUserById(secUser.getUserId());
        user.setSalt(salt);
        user.setPassword(newMd5Pwd);
        userMapper.updateUser(user);

    }

    public void updateUser(User user) {
        userMapper.updateUser(user);
    }

    public void deleteUserById(long id) throws DataAccessException, IOException {
        userMapper.deleteUserById(id);
    }


    public void updateUserDetail(UserDetail userDetail) {
        SecUserDetails secUser = (SecUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = secUser.getUserId();
        Integer userType = secUser.getUserType();

        if(userDetail.getUserName()!=null){
            try {
                String  f = Pinyin4jUtils.getFirstLetter(userDetail.getUserName());
                userDetail.setFirstLetterOfName(f);
            }catch (Exception e){
                userDetail.setFirstLetterOfName("UNKNOW");
            }
        }

        userDetail.setId(userId);
        userMapper.updateUserDetail(userDetail);
        userMapper.deleteUserContact(userId);
        for (UserContact contact : userDetail.getContactList()) {
            contact.setUserId(userId);
        }
        userMapper.insertUserContacts(userDetail.getContactList());


        if (userType == User.USER_TYPE_COMPANY) {
            if (userDetail.getShippingTypes() != null) {
                userMapper.deleteShippingTypesForCompany(userId);
                if (userDetail.getShippingTypes().size() > 0) {

                    userMapper.insertShippingTypeForCompany(userId, userDetail.getShippingTypes());
                }

            }
        }

        if (userType == User.USER_TYPE_SENDER) {
            if (userDetail.getLines() != null) {
                userMapper.deleteRegularLinesByUserId(userId);
                if (userDetail.getLines().size() > 0) {
                    userMapper.insertRegularLines(userId, userDetail.getLines());
                }

            }
        }


    }

    public  List<User> getAllCompanies(){
        return userMapper.getAllCompanies();
    }
}
